package com.woman.beautylive.presentation.ui.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.mob.tools.utils.UIHandler;
import com.tencent.bugly.crashreport.CrashReport;
import com.woman.beautylive.R;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseActivity;
import com.woman.beautylive.presentation.ui.main.MainActivity;
import com.woman.beautylive.util.Const;
import com.woman.beautylive.util.L;
import com.woman.beautylive.util.troubleshoot.AuthException;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import rx.functions.Action1;

/**
 * 注意：这里使用了Handler。由于ShareSdk授权方法的回调执行在非UI线程，所以需要使用Handler回调到这边才能处理UI操作。
 * 登录页面
 */
public class LoginSelectActivity extends BaseActivity implements Handler.Callback,
        PlatformActionListener, LoginUiInterface {

    private ThirdLoginPresenter presenter;

    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_LOGIN = 2;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR= 4;
    private static final int MSG_AUTH_COMPLETE = 5;

    public static Intent createIntent(Context context){
        return new Intent(context, LoginSelectActivity.class);
    }

    private ImageView mSina,mWechart,mQQ,mPhone;
    private TextView mPrivacy;
    private static int PHONE_REQUEST_CODE = 101;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_select;
    }
    @Override
    protected void init() {
//        sendFinishBroadcast(LOG_TAG);
        presenter = new ThirdLoginPresenter(this);
        setSwipeBackEnable(false);

        LocalDataManager.getInstance().clearLoginInfo();
        //Clear all third authorize
        new QQ(this).removeAccount(true);
        new Wechat(this).removeAccount(true);
//        new SinaWeibo(this).removeAccount(true);
    }
    @Override
    protected void findViews(Bundle savedInstanceState) {
//        mSina = (ImageView)findViewById(R.id.login_select_sina);
        mWechart = (ImageView)findViewById(R.id.login_select_wechart);
        mQQ = (ImageView)findViewById(R.id.login_select_qq);
        mPhone = (ImageView)findViewById(R.id.login_select_phone);
        mPrivacy = (TextView)findViewById(R.id.login_select_privacy);
        mPrivacy.setText(getString(R.string.login_select_privacy, getString(R.string.app_name)));
    }
    @Override
    protected void setListeners() {
        super.setListeners();
//        RxView.clicks(mSina).throttleFirst(Const.VIEW_THROTTLE_TIME,
//                TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
//            @Override
//            public void call(Void aVoid) {
////               toastShort(R.string.commen_notmake);
//                authorize(new SinaWeibo(LoginSelectActivity.this));
//            }
//        });
        RxView.clicks(mWechart).throttleFirst(Const.VIEW_THROTTLE_TIME,
                TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
//                toastShort(R.string.commen_notmake);
                authorize(new Wechat(LoginSelectActivity.this));
            }
        });
        subscribeClick(mQQ, new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                authorize(new QQ(LoginSelectActivity.this));
            }
        });
        RxView.clicks(mPhone).throttleFirst(Const.VIEW_THROTTLE_TIME,
                TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                Intent i = LoginActivity.createIntent(LoginSelectActivity.this);
                startActivity(i);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.unsubscribeTasks();
    }

    @Override
    protected void onResume() {
//        MobclickAgent.onPageStart("登录");
        super.onResume();
    }

    @Override
    protected void onPause() {
//        MobclickAgent.onPageEnd("登录");
        super.onPause();
    }

    @Override
    public void startActivityAndFinishOthers() {
        startActivity(MainActivity.createIntent(LoginSelectActivity.this));
        sendFinishBroadcast(MainActivity.class.getSimpleName());
    }

    private void authorize(final Platform plat) {
        showLoadingDialog();
        if(plat.isValid()) {
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
                return;
            }
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(false);
        plat.showUser(null);
    }

    // -----------------  PlatformActionListener BEGIN ----------------

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Log.i("mrl","登录"+platform+"action"+action+"res "+res);
        if (action==Platform.ACTION_USER_INFOR){
            UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, LoginSelectActivity.this);
            L.i(LOG_TAG, "platform=%s, res=%s", platform, res);
            presenter.thirdLogin(platform, res);
        }
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        if (action==Platform.ACTION_USER_INFOR){
            UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, LoginSelectActivity.this);
            L.e(LOG_TAG, "Error authorizing...", throwable);
            CrashReport.postCatchedException(new AuthException("Third login exception", throwable));
        }
    }

    @Override
    public void onCancel(Platform platform, int action) {
        if (action==Platform.ACTION_USER_INFOR){
            UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, LoginSelectActivity.this);
        }
    }
    // -----------------  PlatformActionListener END ----------------

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_USERID_FOUND:
                //native userId information
                L.e(LOG_TAG, "This branch should never be executed!");
                toastShort("本地授权获取成功");
                break;
            case MSG_AUTH_COMPLETE:
                dismissLoadingDialog();
                toastShort("授权成功");
                break;
            case MSG_AUTH_CANCEL:
                dismissLoadingDialog();
                toastShort("您取消了登录");
                break;
            case MSG_AUTH_ERROR:
                dismissLoadingDialog();
                toastShort("授权失败！");
                break;
            default:
                break;
        }
        return false;
    }

}
